package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: 微信小程序页面调用API*
 */

public class apiWXMiniPURL implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWXMiniPURL.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 获取接口调用方式及参数
        String getMethod = request.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        //  入参为空
        if (KHUtil.isNull(inData)) {
            log.debug("入参为空-无法完成操作!");
            result.put("errcode", -2);
            result.put("errmsg", "入参为空-无法完成操作!");

            return result.toString();
        }

        try {

            String DOMAIN = KHDBConfig.getAPIURL(eliteBean, "EliteInner-API");
            JSONObject apiTokenJson = JSONObject.fromObject(Util.doHttpGet(DOMAIN + "/apiGetToken?appid=WXM", "UTF-8", 5000, 0));
            log.debug("小程序Token信息：" + apiTokenJson.toString());
            String access_token = apiTokenJson.getJSONObject("data").getString("access_token");

            String wxmURL = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + access_token;

            // 处理头文件
            Map<String, String> headerMap = new HashMap<String, String>();
            headerMap.put("Accept", "application/json");
            headerMap.put("Content-Type", "application/json");

            String sendResult = Util.doHttpPost(wxmURL, inData, "UTF-8", 10000, 0);
            result = JSONObject.fromObject(sendResult);
            log.info("调用处理结果：" + result.toString());

        } catch (Exception e) {
            log.error("数据处理错误:", e);
            result.put("errcode", -1);
            result.put("errmsg", "数据处理错误[" + e.getMessage() + "]");
        }

        return result.toString();
    }

}
